import axios from 'axios';
import { baseUrl } from "@/const"
import { Message, MessageBox } from 'element-ui';
// axios.defaults.baseURL = process.env.TE_API

axios.defaults.baseURL = baseUrl            // 服务器


// let token = window.sessionStorage.getItem('token') ? window.sessionStorage.getItem('token') : ''

const service = axios.create({
  withCredentials: false,
  timeout: 60000,
  headers: {
    'Content-Type': 'application/json',
  },
})

service.interceptors.request.use(
  config => {
    // header 中 带入 token
    if (config.token) {
      config.headers.Authorization = config.token
    }
    return config
  },
  
  error => {
    // Do something with request error 
    Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data;
    if (res.code == 200 || res.code == 1000 || res.status == 200 || res.message == 'success') {
      return res
    }

    else {
      Message({
        message: res.repMsg || res.message,
        type: 'error',
        duration: 3 * 1000
      })
      return res;
    }
  },
  error => {
    var errorStatus = error.response.code;
    var errorData = error.response.data;
    var messageTxt = "";
    if (errorStatus != 200) {
      messageTxt = "服务器内部错误，请联系管理员";
    } else {
      messageTxt = '失败原因：' + errorData.code + '--' + errorData.repMsg;
    }
    Message({
      message: messageTxt,
      type: 'error',
      duration: 5 * 1000
    })
  }
)

export default service
